// pages/planlist/planlist.js
import api from '../../utils/api';
var util = require('../../utils/util.js');
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        planList: null,
        detailinfo: null,
        dong: null,
        census: [0, 0, 0],
        is_day: ['unday', 'unday', 'unday', 'unday', 'unday', 'unday', 'unday'],
        daytest: '今日',
        index: 0,
        indextwo:0,
        show: true,
        minDate: new Date(2022, 9, 1).getTime(),
        maxDate: new Date(2022, 9, 31).getTime(),
        time: null,
        yy: '0000',
        mm: '00',
        itemShow: null,
        HStab: 'HStab',
        dayNumber:[1,2,3,4,5,6,7]
    },
    deleteInfoTap() {
        Dialog.confirm({
                title: '神明大人，确定删除任务吗？'
            })
            .then(() => {
                let value = {
                    plan_id: this.data.detailinfo.plan_id,
                    is_delete: 1
                }
                api.postUpdatePlan(value).then((res) => {
                    // console.log(res)
                    this.setData({
                        dong: 'dongChu'
                    })
                    this.inital(this.data.detailinfo.date)
                })
            })
            .catch(() => {});
    },
    updateInfoTap() {
        if (this.data.detailinfo.rest == '1') {
            Toast('已打卡信息不支持修改~');
        } else {
            var model = JSON.stringify(this.data.detailinfo);
            wx.navigateTo({
                url: '/pages/add/add?model=' + model + '&is_jia=' + 0,
            })
        }
    },
    tabTap() {
        this.setData({
            itemShow: this.data.itemShow == null ? 'itemShow' : null,
            HStab: this.data.HStab == 'HStab' ? null : 'HStab'
        })
        let time = util.formatTime(new Date());
        this.inital(time)
    },
    minuteTap() {
        let bian = 'time[' + (1) + ']'
        let bian2 = 'time[' + (0) + ']'
        if (parseInt(this.data.time[1]) == 1) {
            this.setData({
                [bian2]: parseInt(this.data.time[0]) - 1,
                [bian]: 12
            })
        } else {
            this.setData({
                [bian]: parseInt(this.data.time[1]) - 1
            })
        }
        this.dateFor(this.data.time)
    },
    addTap() {
        let bian = 'time[' + (1) + ']'
        let bian2 = 'time[' + (0) + ']'
        if (parseInt(this.data.time[1]) == 12) {
            this.setData({
                [bian2]: parseInt(this.data.time[0]) + 1,
                [bian]: 1
            })
        } else {
            this.setData({
                [bian]: parseInt(this.data.time[1]) + 1
            })
        }
        this.dateFor(this.data.time)
    },
    dateSelTap(e) {
        // 需要格式化
        const d = new Date(e.detail)
        const resDate = d.getFullYear() + '-' + this.p((d.getMonth() + 1)) + '-' + this.p(d.getDate())
        this.inital(resDate)
    },
    planDetailTap(e) {
        this.setData({
            detailinfo: this.data.planList[e.currentTarget.dataset.index],
            dong: 'dongJin',
            indextwo:e.currentTarget.dataset.index
        })
    },
    detailClose() {
        this.setData({
            dong: 'dongChu'
        })
    },
    inital(time) {
        let value = {
            start: time,
            end: time
        }
        this.setData({
            planList: null
        })
        api.postSelectPlan(value).then((res) => {
            this.setData({
                planList: res.result
            })
            for (const i in this.data.planList) {
                let dates = this.data.planList[i].date.substring(0, 10)
                let datelist = dates.split('-')
                datelist[2] = parseInt(datelist[2]) + 1
                if (datelist[2] / 10 < 1) {
                    datelist[2] = `0${datelist[2]}`
                }
                dates = datelist.join("-")
                let planList = 'planList[' + (i) + '].date'
                this.setData({
                    [planList]: dates
                })
            }
        })

    },
    one(e) {
        let ids = e.currentTarget.dataset.index - 1
        let i = this.data.index

        for (let index = 0; index < this.data.is_day.length; index++) {
            if (this.data.is_day != 'unday') {
                let day = 'is_day[' + (index) + ']'
                this.setData({
                    [day]: 'unday'
                })
                // i = index
            }
        }
        // this.data.index代表今日的值
        let daySel = 'is_day[' + (ids) + ']'
        this.setData({
            [daySel]: 'day',
            daytest: this.data.index > ids ? `前${this.data.index-ids}日` : `后${ids-this.data.index}日`,
            dong: null
        })
        if (this.data.index == ids) {
            this.setData({
                daytest: '今日'
            })
        }
        // 发请求
        let time = util.formatTime(new Date());
        let timelist = time.split('-')
        // 如果比今日大就加上
        timelist[2] = i < ids ? parseInt(timelist[2]) + (ids-i): parseInt(timelist[2]) - (i - ids)
        if (parseInt(timelist[2]/10)<1) {
            timelist[2] = `0${timelist[2]}`
        }
        timelist = timelist.join("-")
        this.inital(timelist)

    },
    startTap() {
        if (app.globalData.userInfo.email != ''&&app.globalData.userInfo.email != null) {
            let info = 'detailinfo.is_Start'
            let Iteminfo = 'planList[' + (this.data.indextwo) + '].is_Start'
            this.setData({
                [info]: this.data.detailinfo.is_Start == 1 ? 0 : 1,
                [Iteminfo]: this.data.planList[this.data.indextwo].is_Start == 1 ? 0 : 1
            })
            // 发请求
            let value = {
                plan_id: this.data.detailinfo.plan_id,
                is_Start: this.data.detailinfo.is_Start
            }
            api.postUpdatePlan(value).then((res) => {
                Toast('设置成功~');
            })
        } else {
            Toast('请先在‘我的’页面设置邮箱~');
        }

    },
    endTap() {
        if (app.globalData.userInfo.email != ''&&app.globalData.userInfo.email != null) {
            let info = 'detailinfo.is_End'
            let Iteminfo = 'planList[' + (this.data.indextwo) + '].is_End'
            this.setData({
                [info]: this.data.detailinfo.is_End == 1 ? 0 : 1,
                [Iteminfo]: this.data.planList[this.data.indextwo].is_End == 1 ? 0 : 1
            })
            let value = {
                plan_id: this.data.detailinfo.plan_id,
                is_End: this.data.detailinfo.is_End
            }
            api.postUpdatePlan(value).then((res) => {Toast('设置成功~');})
        } else {
            Toast('请先在‘我的’页面设置邮箱~');
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let time = util.formatTime(new Date());
        this.inital(time)
        this.weekTitle(time)
        let day = new Date().getDay();
        if (day==0) {
            day = 6
        }
        let arr = 'is_day[' + (day-1) + ']'
        let list = [app.globalData.userInfo.totalTime, app.globalData.userInfo.daytotal, app.globalData.userInfo.days]
        let timelist = time.split('-')
        this.setData({
            [arr]: 'day',
            census: list,
            index: day-1,
            time: timelist,
            dong: null
        })
        let bShow = ''
        wx.setStorageSync('bShow', false)
        this.dateFor(timelist)
    },
    weekTitle(time){
        let weekDays = this.getWeekDay(time)
        for (let [k,v] of weekDays.entries()) {
            let valV = v.split('-')
            let dayNumber = 'dayNumber['+(k)+']' 
            this.setData({
                [dayNumber]:valV[2]
            })
        }
    },
    getWeekDay(dateString) {
        let dateStringReg = /^\d{4}[/-]\d{1,2}[/-]\d{1,2}$/;

        if (dateString.match(dateStringReg)) {
            let presentDate = new Date(dateString),
                today = presentDate.getDay() !== 0 ? presentDate.getDay() : 7;

            return Array.from(new Array(7), function (val, index) {
                return formatDate(new Date(presentDate.getTime() - (today - index - 1) * 24 * 60 * 60 * 1000));
            });

        } else {
            throw new Error('dateString should be like "yyyy-mm-dd" or "yyyy/mm/dd"');
        }

        function formatDate(date) {
            return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
        }
    },
    dateFor(timelist) {
        let daylist = this.getDay(parseInt(timelist[0]), parseInt(timelist[1]))
        this.setData({
            minDate: new Date(timelist[0], parseInt(daylist[0]) - 1, 1).getTime(),
            maxDate: new Date(timelist[0], parseInt(daylist[0]) - 1, daylist[1]).getTime(),
            yy: timelist[0],
            mm: parseInt(daylist[0])
        })
    },
    getDay(year, month) {
        if (year != '' && month != '') {
            var firstDay = new Date(year, month - 1, 1) //这个月的第一天
            var currentMonth = firstDay.getMonth() //取得月份数
            var d = new Date(firstDay.getFullYear(), currentMonth + 1, 0) //是0而不是-1
            const resDate = this.p(d.getDate())
            const monDate = this.p((d.getMonth() + 1))
            return [monDate, resDate]
        }
    },
    p(s) {
        return s < 10 ? '0' + s : s
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        wx.setStorageSync('aShow', true)
        var page = this;
        let bShow = ''
        //获取存储信息
        wx.getStorage({
            key: 'bShow',
            success: function (res) {
                bShow = res.data;
                if (bShow) {
                    page.inital(wx.getStorageSync('timeP'))
                    wx.setStorageSync('bShow', false)
                    page.setData({
                        dong: null
                    })
                }
            }
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})